package cn.wolfcode.luowowo.website.param;

import cn.wolfcode.luowowo.cache.handler.UserInfoRedisHandler;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UserContext;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2019/7/8.
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        System.out.println(methodParameter.hasParameterAnnotation(UserParam.class));
        return methodParameter.hasParameterAnnotation(UserParam.class) && methodParameter.getParameterType() == UserInfo.class;
    }
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Cookie cookie = UserContext.getCookie(request, UserInfoRedisHandler.TOKEN_COOKIE);
        UserInfo userInfo = null;
        if(cookie != null){
            userInfo = userInfoRedisService.get(UserInfoRedisHandler.USER_INFO_REDIS_HANDLER, cookie.getValue());
        }
        return userInfo;
    }
}